//
//  CSHomeTableViewController.m
//  classroom
//
//  Created by Macx on 16/7/30.
//  Copyright © 2016年 LiuZhuo. All rights reserved.
//

#import "CSHomeTableViewController.h"
#import "HcdGuideView.h"
#import "CSBuildManager.h"
#import "CSBuildPickerView.h"
#import "TFHpple.h"
#import "CSTransBuild.h"
#import "CSTranstrueBuild.h"
@interface CSHomeTableViewController ()<MXListViewDataSource,MXListViewDelegate>
@property (nonatomic,strong) CSBuildPickerView *regionPickerView;
@property (nonatomic,strong) CSBuildPickerView *datePickerView;
@property (nonatomic,strong) UILabel *addressLabel;
@property (nonatomic,strong) UILabel *dateLabel;
@property (nonatomic,strong) UILabel * oldaddressLabel;
@property (nonatomic,strong) UILabel * olddateLabel;

@property(nonatomic,strong)NSMutableArray * nameArr ;
@property(nonatomic,strong)NSMutableArray * typeArr ;
@property(nonatomic,strong)NSMutableArray * countArr ;
@property(nonatomic,strong)NSMutableArray * dayArr ;
@property(nonatomic,strong)NSData *htmlData;
@end

@implementation CSHomeTableViewController
+(void)initialize
{
    [[MXListView appearance]setSeparatorColor:[UIColor whiteColor]];
    [[MXListView appearance]setBackgroundColor:[UIColor lightGrayColor]];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    DDLogDebug(@"-=-=--=-%@",NSHomeDirectory());
    
    self.tableView.separatorStyle =UITableViewCellSeparatorStyleNone;
        // 新特性
        [self new];
        
        
        
        // 设置两侧导航条
        [self nav];
        
        
        // 设置主界面
        [self home];
    
 
    
}
-(void)new{
    NSMutableArray *images = [NSMutableArray new];
    
    [images addObject:[UIImage imageNamed:@"1"]];
    [images addObject:[UIImage imageNamed:@"2"]];
    [images addObject:[UIImage imageNamed:@"3"]];
    
    [[HcdGuideViewManager sharedInstance] showGuideViewWithImages:images
                                                   andButtonTitle:@"立即体验"
                                              andButtonTitleColor:[UIColor blackColor]
                                                 andButtonBGColor:[UIColor lightGrayColor]
                                             andButtonBorderColor:[UIColor lightGrayColor]];
//andButtonTitleColor:[UIColor whiteColor]
//andButtonBGColor:[UIColor clearColor]
//andButtonBorderColor:[UIColor whiteColor]];
    
    
}
-(void)nav{
    _addressLabel = [[UILabel alloc]init];
    _dateLabel = [[UILabel alloc]init];
    _oldaddressLabel = [[UILabel alloc]init];
    _olddateLabel = [[UILabel alloc]init];
    
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    NSString * area = [userDefaults objectForKey:@"buildName"];
    NSRange  range = [area rangeOfString:@" "];
    NSString * areaNow = nil;
    if (area==nil) {
        areaNow =@"尔雅楼";
        area =@"葫芦岛校区 尔雅楼";
    }else{
        
        areaNow = [area substringFromIndex:range.location+1];
    }
    NSString * date = [userDefaults objectForKey:@"dateName"];
    if (date==nil) {
        date=@"第1周 周一";
    }else{
        date = [[[CSGetTrueDay alloc]init] dateName:date];
    }
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:areaNow style:UIBarButtonItemStylePlain target:self action:@selector(chooseArea:)];
    _addressLabel.text =area;
    _oldaddressLabel.text = _addressLabel.text;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:date style:UIBarButtonItemStylePlain target:self action:@selector(chooseDate:)];
    _dateLabel.text = self.navigationItem.rightBarButtonItem.title;
    _olddateLabel.text = _dateLabel.text;
    
    
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    
    
}


-(void)home{
    _listView = [[MXListView  alloc]initWithFrame:self.view.frame];
    _listView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    _listView.dataSource = self;
    _listView.delegate = self;
    _listView.selectionStyle = MXListViewSelectionStyleNone;
    [self.view addSubview:_listView];
    _listView.contentScrollView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshInfo:)];
    
    
             [self.listView.contentScrollView.mj_header beginRefreshing];
         
    
   
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
-(void)chooseArea:(UIBarButtonItem *)btn{
    NSString *address = _addressLabel.text;
    NSArray *array = [address componentsSeparatedByString:@" "];
    
    NSString *area = @"";//校区
    NSString *build = @"";//教学楼
    if (array.count > 1) {
        area = array[0];
        build = array[1];
    } else if (array.count > 0) {
        build = array[0];
    }
    [self.regionPickerView showPickerWithAreaName:area buildName:build];
 
}
-(void)chooseDate:(UIBarButtonItem *)btn{
    NSString *date = _dateLabel.text;
    NSArray *array = [date componentsSeparatedByString:@" "];
    
    NSString *week = @"";//校区
    NSString *day = @"";//教学楼
    if (array.count > 1) {
        week = array[0];
        day = array[1];
    } else if (array.count > 0) {
        day = array[0];
    }
    
    [self.datePickerView showPickerWithWeekName:week dayName:day];
    
}
- (CSBuildPickerView *)regionPickerView {
    if (!_regionPickerView) {
        _regionPickerView = [[CSBuildPickerView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
        
        __weak typeof(self) wself = self;
        _regionPickerView.completion = ^(NSString *areaName,NSString *buildName) {
            __strong typeof(wself) self = wself;
            self.addressLabel.text = [NSString stringWithFormat:@"%@ %@",areaName,buildName];
            if ([self.addressLabel.text hasSuffix:@"楼"]) {
                NSRange  range = [self.addressLabel.text rangeOfString:@" "];
                NSString * areaNow = [self.addressLabel.text substringFromIndex:range.location+1];
                self.navigationItem.leftBarButtonItem.title = areaNow;
                [self.tableView reloadData];
                if (_oldaddressLabel.text != _addressLabel.text) {
                     [self.listView.contentScrollView.mj_header beginRefreshing];
                    self.oldaddressLabel.text = self.addressLabel.text;
                }
               
            }
            
        };
        [self.tabBarController.view addSubview:_regionPickerView];
        
    }
    
    return _regionPickerView;
}
-(CSBuildPickerView *)datePickerView{
    if (!_datePickerView) {
        _datePickerView = [[CSBuildPickerView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
        
        __weak typeof(self) wself = self;
        
        
        _datePickerView.dateCompletion= ^(NSString *weekName,NSString *dayName) {
            __strong typeof(wself) self = wself;
            self.dateLabel.text = [NSString stringWithFormat:@"%@ %@",weekName,dayName];
            if (self.dateLabel.text.length>4) {
                self.navigationItem.rightBarButtonItem.title=self.dateLabel.text;
                [ self.tableView reloadData];
                if (_olddateLabel.text != _dateLabel.text) {
                    [self.listView.contentScrollView.mj_header beginRefreshing];
                    self.olddateLabel.text = self.dateLabel.text;
                }
                
            }
        };
        
        [self.tabBarController.view addSubview:_datePickerView];
        
    }
    
    return _datePickerView;
    
}
-(void)refreshInfo:(UIRefreshControl *)ref{
    NSMutableDictionary * dict1 = [NSMutableDictionary dictionary];
    dict1[@"build"]= _addressLabel.text;
    dict1[@"week"]= _dateLabel.text;
    NSDate  * currentDate = [NSDate date];
    NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat = @"YYYY-MM-dd";
    NSString * date = [formatter stringFromDate:currentDate];
    dict1[@"date"] = date;
    
   NSDictionary * dict =  [[SNSQLiteTools shareSqliteTools]statuses:dict1];
    if (dict!= nil) {
        NSString * dayName = [_dateLabel.text substringFromIndex:_dateLabel.text.length-1];
        NSString * alaboName = [CSTransAlabo translation:dayName];
        _nameArr = dict[@"name"];
        _typeArr = dict[@"type"];
        _countArr = dict[@"count"];
        _dayArr = [dict objectForKey:alaboName];
        
        [self.listView reloadData];
        [self.listView.contentScrollView.mj_header endRefreshing];

    }else {
//         dict = [[[CSNetWork alloc]init] netWork:_addressLabel.text dateName:_dateLabel.text];
        
        NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
        NSString *  ison = [userDefaults objectForKey:@"仅Wifi状态下连网"];
        BOOL ison3G = [userDefaults boolForKey:@"网络状态为3G"];
        DDLogDebug(@"%@",ison);
        DDLogDebug(@"%d",ison3G);
        if ([ison isEqualToString:@"开"]&ison3G) {
//
            dict = nil;
            NSString * dayName = [_dateLabel.text substringFromIndex:_dateLabel.text.length-1];
            NSString * alaboName = [CSTransAlabo translation:dayName];
            _nameArr = dict[@"name"];
            _typeArr = dict[@"type"];
            _countArr = dict[@"count"];
            _dayArr = [dict objectForKey:alaboName];
            
            [self.listView reloadData];
            [self.listView.contentScrollView.mj_header endRefreshing];
            return;
        }
        
        NSRange  range = [_addressLabel.text rangeOfString:@" "];
        NSString  *   areaNow = [_addressLabel.text substringFromIndex:range.location+1];
        
        NSString * buildId = [CSTransBuild translation:areaNow];
        NSString * trueBuildName = [CSTranstrueBuild translation:areaNow];
        NSString *  weekName = nil;
        
        if ( [self isPureInt:[_dateLabel.text substringWithRange:NSMakeRange(1, 2)]] ) {
            weekName = [_dateLabel.text substringWithRange:NSMakeRange(1, 2)];
        }else{
            weekName = [_dateLabel.text substringWithRange:NSMakeRange(1, 1)] ;
        }
        NSMutableArray * strArray = [NSMutableArray array];
        
        
        NSString * urlStr = [NSString stringWithFormat:@"http://60.18.131.131:11180/academic/manager/teachresource/schedule/export_room_schedule_detail.jsp?weeks=%@&buildingid1=%@&buildingname=%@",weekName,buildId,trueBuildName] ;
        DDLogDebug(@"%@",urlStr);
        urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSMutableDictionary * dict = [NSMutableDictionary dictionary];
        
        AFHTTPSessionManager * manager = [[AFHTTPSessionManager alloc]init];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        [manager GET:urlStr parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            self.htmlData = responseObject;
            DDLogDebug(@"success-=-=-=");
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                TFHpple *xpathParser = [[TFHpple alloc]initWithHTMLData:_htmlData];
                NSArray * dataArray = [xpathParser searchWithXPathQuery:@"//td"];
                for (TFHppleElement * httpElement in dataArray) {
                    [strArray addObject:httpElement.text];
                }
                if (strArray.count==0) {
                    
                    
                }
                [strArray removeObjectsInRange:NSMakeRange(0, 12)];
                NSMutableArray * nameArr = [NSMutableArray array];
                NSMutableArray * countArr = [NSMutableArray array];
                NSMutableArray * typeArr = [NSMutableArray array];
                NSMutableArray * monArr = [NSMutableArray array];
                NSMutableArray * tuesArr = [NSMutableArray array];
                NSMutableArray * wesArr = [NSMutableArray array];
                NSMutableArray * thuArr = [NSMutableArray array];
                NSMutableArray * friArr = [NSMutableArray array];
                NSMutableArray * satArr = [NSMutableArray array];
                NSMutableArray * sunArr = [NSMutableArray array];
                for (int i = 0; i<strArray.count/10; i++) {
                    NSMutableArray * arr = [NSMutableArray array];
                    [arr removeAllObjects];
                    for (int j= i*(10); j<(i +1)*10; j++) {
                        
                        [arr addObject:strArray[j]];
                    }
                    [nameArr addObject:arr[0]];
                    [countArr addObject:arr[1]];
                    [typeArr addObject:arr[2]];
                    [monArr addObject:arr[3]];
                    [tuesArr addObject:arr[4]];
                    [wesArr addObject:arr[5]];
                    [thuArr addObject:arr[6]];
                    [friArr addObject:arr[7]];
                    [satArr addObject:arr[8]];
                    [sunArr addObject:arr[9]];
                }
                
                [dict setObject:nameArr forKey:@"name"];
                [dict setObject:countArr forKey:@"count"];
                [dict setObject:typeArr forKey:@"type"];
                [dict setObject:monArr forKey:@"1"];
                [dict setObject:tuesArr forKey:@"2"];
                [dict setObject:wesArr forKey:@"3"];
                [dict setObject:thuArr forKey:@"4"];
                [dict setObject:friArr forKey:@"5"];
                [dict setObject:satArr forKey:@"6"];
                [dict setObject:sunArr forKey:@"7"];
                //            return dict;
                if (dict==nil) {
                    
                    [SVProgressHUD showErrorWithStatus:@"当前无可用网络和缓存"];
                    [self performSelector:@selector(diss) withObject:nil afterDelay:1.5];
                    
                }else{
                    [[SNSQLiteTools shareSqliteTools]insertStatus:dict withDict1:dict1 ];
                }
                NSString * dayName = [_dateLabel.text substringFromIndex:_dateLabel.text.length-1];
                NSString * alaboName = [CSTransAlabo translation:dayName];
                _nameArr = dict[@"name"];
                _typeArr = dict[@"type"];
                _countArr = dict[@"count"];
                _dayArr = [dict objectForKey:alaboName];
                
                [self.listView reloadData];
                [self.listView.contentScrollView.mj_header endRefreshing];


                
            });
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            DDLogDebug(@"%@",error);
        }];
        

        
        
        
      
    }
    
   
   }
-(void)diss{
    [SVProgressHUD dismiss];
}
#pragma delegate

-(CGFloat)listView:(MXListView *)listView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 45;
}
-(CGFloat)listView:(MXListView *)listView widthForCulumnAtIndex:(NSInteger)index
{
    if (index==0||index==6||index==7) {
        return 90;
    }
    else{
        return ([UIScreen mainScreen].bounds.size.width - 90)/5;
    }
    
    
}
-(CGFloat)listView:(MXListView *)listView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}
-(CGFloat)listView:(MXListView *)listView heightForFooterInSection:(NSInteger)section{
    
    return 115;
    
    
}

-(UIView *)listView:(MXListView *)listView reuseViewForHeader:(UIView *)reuseView inSection:(NSInteger)section inColumn:(NSInteger)inColumn
{
    NSArray *arr = @[@"大节",@"第1节",@"第2节",@"第3节",@"第4节",@"第5节",@"教室类型",@"教室容量"];
    if (!reuseView) {
        reuseView = [[UILabel alloc]init];
    }
    
    ((UILabel *)reuseView).text = arr[inColumn];
    
    ((UILabel *)reuseView).textColor = [UIColor whiteColor];
    ((UILabel *)reuseView).textAlignment = NSTextAlignmentCenter;
    ((UILabel *)reuseView).font = [UIFont systemFontOfSize:16];
    reuseView.backgroundColor = [UIColor grayColor];
    return reuseView;
}

#pragma dataSource
-(NSInteger)numberOfSectionsInListView:(MXListView *)listView
{
    return 1;
}
-(NSInteger)listView:(MXListView *)listView numberOfRowsInSection:(NSInteger)section
{

        return self.nameArr.count;
    
    
}
-(NSInteger)numberOfColumnsEachRowInListView:(MXListView *)listView
{
    return 8;
}
-(UIView *)listView:(MXListView *)listView reuseView:(UIView *)reuseView indexPath:(NSIndexPath *)indexPath inColumn:(NSInteger)inColumn
{
    if (reuseView==nil) {
        reuseView = [[UILabel alloc]init];
        
    }
    
    if (inColumn == 0) {
        ((UILabel *)reuseView).backgroundColor = [UIColor grayColor];
    }else
    {
        ((UILabel *)reuseView).backgroundColor = [UIColor lightGrayColor];
    }
    ((UILabel *)reuseView).font = [UIFont systemFontOfSize:14];
    
    if (inColumn==0) {
        ((UILabel *)reuseView).text = _nameArr[indexPath.row];
        NSString * str = _nameArr[indexPath.row];
        if (str.length>7) {
            ((UILabel *)reuseView).font = [UIFont systemFontOfSize:9];
        }
    }else if(inColumn==6) {
        ((UILabel *)reuseView).text = _typeArr[indexPath.row];
        NSString * str = _typeArr[indexPath.row];
        if (str.length>6) {
            ((UILabel *)reuseView).font = [UIFont systemFontOfSize:9];
        }
    } else if (inColumn==7) {
        ((UILabel *)reuseView).text = _countArr[indexPath.row];
    }
    else{
        
        NSString * str =_dayArr[indexPath.row];
        NSString * str1 = [str substringWithRange:NSMakeRange(2*inColumn +1, 1)];
        if ([@"12345" rangeOfString:str1].location != NSNotFound) {
            ((UILabel *)reuseView).text =@"有课";
        }else{
            ((UILabel *)reuseView).text =nil;
        }
        
    }
    
    ((UILabel *)reuseView).textColor = [UIColor whiteColor];
    ((UILabel *)reuseView).textAlignment = NSTextAlignmentCenter;
    return reuseView;
}

//#pragma mark - 本地推送
//- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
//{
//    //1.创建本地通知  特定的时间显示出来 (定制)
//    UILocalNotification *local = [[UILocalNotification alloc]init];
//    //2.初始化  属性
//    local.alertBody = @"教室占用情况已更新，点击查看";
//    local.alertAction = @"查看";
//    local.fireDate = [NSDate dateWithTimeIntervalSinceNow:5];
//    local.applicationIconBadgeNumber = 10;
//    local.category = @"look";
//    local.userInfo = @{@"name" : @"刘卓"};
//    //3.定制  使用
//    [[UIApplication sharedApplication]scheduleLocalNotification:local];
//    //4.知道啥时候接收了通知
//    //代理
//    
//}
//
#pragma mark - 懒加载
-(NSMutableArray *)nameArr{
    if (_nameArr==nil) {
        _nameArr = [NSMutableArray array];
    }
    return _nameArr;
}
-(NSMutableArray *)typeArr{
    if (_typeArr==nil) {
        _typeArr = [NSMutableArray array];
    }
    return _typeArr;
}
-(NSMutableArray *)countArr{
    if (_countArr==nil) {
        _countArr = [NSMutableArray array];
    }
    return _countArr;
}
-(NSMutableArray *)dayArr{
    if (_dayArr==nil) {
        _dayArr = [NSMutableArray array];
    }
    return _dayArr;
}
// 判断字符串是否为整形数字
- (BOOL)isPureInt:(NSString *)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return [scan scanInt:&val] && [scan isAtEnd];
}
@end
